package com.jc.service.common.util;

import com.jc.service.common.config.JwtConfig;
import com.jc.service.common.model.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * JWT工具类，用于生成和解析JWT令牌
 */
@Component
public class JwtUtil {

    private final SecretKey secretKey;
    private final long expiration;
    private final Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    public JwtUtil(JwtConfig jwtConfig) {
        this.secretKey = jwtConfig.secretKey();
        this.expiration = jwtConfig.getExpiration();
    }

    /**
     * 从令牌中获取用户名
     */
    public String getLoginNameFromToken(String token) {
        return getClaimFromToken(token, claims -> claims.get("loginName", String.class));
    }

    /**
     * 从令牌中获取用户全名
     */
    public String getFullNameFromToken(String token) {
        return getClaimFromToken(token, claims -> claims.get("fullName", String.class));
    }

    /**
     * 从令牌中获取租户ID
     */
    public String getTenantIdFromToken(String token) {
        return getClaimFromToken(token, claims -> claims.get("tenantId", String.class));
    }

    /**
     * 从令牌中获取过期时间
     */
    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    /**
     * 从令牌中获取声明
     */
    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    /**
     * 从令牌中获取所有声明
     */
    private Claims getAllClaimsFromToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(secretKey)
                .build()
                .parseClaimsJws(token)
                .getBody();
        return claims;
    }

    /**
     * 检查令牌是否过期
     */
    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    /**
     * 验证令牌
     */
    public Boolean validateToken(String token) {
        return !isTokenExpired(token);
    }

    /**
     * 从令牌中获取用户信息
     */
    public LoginUser getUserInfoFromToken(String token) {
        if (token == null || token.isEmpty()) {
            return null;
        }

        try {
            String loginName = getLoginNameFromToken(token);
            String fullName = getFullNameFromToken(token);
            String tenantId = getTenantIdFromToken(token);

            return new LoginUser(loginName, fullName, tenantId);
        } catch (Exception e) {
            logger.error("获取用户信息是出现异常：{}", e);
            return null;
        }
    }
}